package com.tnovoselec.android.fragment;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.io.IOUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.actionbarsherlock.app.SherlockFragment;

public class WebViewFragment extends SherlockFragment {

	private Uri uri;
	private WebView webview;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		uri = activity.getIntent().getData();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		webview = createWebView(inflater, container, savedInstanceState);
		return webview;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		if (uri != null && webview != null) {
			new WebCache().execute();
		}
	}

	/**
	 * Override this method to create custom {@link WebView}
	 * 
	 * @param inflater
	 * @param container
	 * @param savedInstanceState
	 * @return
	 */
	protected WebView createWebView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		final WebView webView = new WebView(container.getContext());
		webView.getSettings().setJavaScriptEnabled(true);
		webView.setWebViewClient(new NTHWebViewClient());
		webView.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN && webView.canGoBack()) {
					webView.goBack();
					return true;
				}
				return false;
			}
		});
		return webView;
	}

	private class WebCache extends AsyncTask<Void, Void, Boolean> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			getActivity().setProgressBarIndeterminateVisibility(Boolean.TRUE);

			final String url = uri.toString();
			final String filename = getFilename(url);

			InputStream fis = null;
			final File file = new File(getActivity().getFilesDir(), filename);

			if (file.exists() && file.canRead() && file.length() > 0) {
				try {
					fis = new FileInputStream(file);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}
			if (fis == null) {
				try {
					fis = getActivity().getAssets().open(filename);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (fis != null) {
				try {
					final String data = IOUtils.toString(fis);
					webview.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			try {
				fis.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			final String url = uri.toString();
			final String filename = getFilename(url);

			try {
				final URLConnection conn = new URL(url).openConnection();
				final File file = new File(getActivity().getFilesDir(), filename);

				if (isConnected()) {
					file.createNewFile();
					final InputStream is = conn.getInputStream();
					final FileOutputStream fos = new FileOutputStream(file);
					IOUtils.copy(is, fos);
					is.close();
					fos.close();
					return true;
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return false;
		}

		@Override
		protected void onPostExecute(Boolean result) {
			if (result) {
				final String url = uri.toString();
				final String filename = getFilename(url);

				FileInputStream fis;
				try {
					fis = new FileInputStream(new File(getActivity().getFilesDir(), filename));
					final String data = IOUtils.toString(fis);
					webview.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);
					webview.clearHistory();
					fis.close();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			getActivity().setProgressBarIndeterminateVisibility(Boolean.FALSE);
			super.onPostExecute(result);
		}

		private String getFilename(String url) {
			// return "web-" + Locale.getDefault().getLanguage() + "-" +
			// url.hashCode() + ".html";
			return "fajl" + url.hashCode() + ".html";

		}

	}

	private class NTHWebViewClient extends WebViewClient {

		public NTHWebViewClient() {
			super();
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			if (!TextUtils.isEmpty(url)) {
				if (url.startsWith("mailto:")) {
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setData(Uri.parse(url));
					startActivity(intent);
					return true;
				}
			}
			getActivity().setProgressBarIndeterminateVisibility(Boolean.TRUE);
			return super.shouldOverrideUrlLoading(view, url);
		}

		@Override
		public void onPageFinished(WebView view, String uri) {
			getActivity().setProgressBarIndeterminateVisibility(Boolean.FALSE);
		}

	}

	private boolean isConnected() {
		ConnectivityManager manager = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
		if (manager != null) {
			NetworkInfo networkInfo = manager.getActiveNetworkInfo();
			if (networkInfo != null) {
				return networkInfo.isConnected();
			}
		}
		return false;
	}

}
